package autopeople.controller;

import java.io.File;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.w3c.dom.Document;

import autopeople.domain.auto.Auto;
import autopeople.service.AutoService;
import autopeople.tools.AutoImporter;
import autopeople.tools.ResourceTool;

@Controller
public class AutoController extends AbstractController {
	protected static Logger logger = Logger.getLogger("controller");

	@Inject
	private AutoService autoService;

	@Inject
	private ResourceTool resourceTool;

	@Inject
	AutoImporter autoImporter;

	@RequestMapping(value = "/auto", method = RequestMethod.GET)
	public ModelAndView readAutosFromXmlFile(Model model) throws Exception {
		logger.debug("Received request to import autos from file");

		// Get file from file-path
		final File autoXmlfile = resourceTool.getFile("/auto.xml");

		// Get normalized document
		final Document doc = autoImporter.getNormalizedDocument(autoXmlfile);

		// TODO rune.forberg Temporary design top parse document and persist
		// autos
		autoImporter.parseAndPersistAutosFromDocument(doc);

		// Retrieve all autos by delegating call to AutoService
		final List<Auto> autos = autoService.getAll();

		// Attach autos to the model
		model.addAttribute("autos", autos);

		// This view lists up all persisted autos from database
		return new ModelAndView("auto");
	}

	/**
	 * Handles and retrieves all autos and show it in a JSP page
	 * 
	 * @return the name of the JSP page
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ModelAndView getAutos(Model model) {
		logger.debug("Received request to show all autos");

		// Retrieve all autos by delegating call to AutoService
		final List<Auto> autos = autoService.getAll();

		// Attach autos to the model
		model.addAttribute("autos", autos);

		// This view lists up all persisted autos from database
		return new ModelAndView("auto");
	}

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest arg0,
			HttpServletResponse arg1) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
}
